package com.example.socket.client;

import com.example.socket.core.Command;
import com.example.socket.core.Header;
import com.example.socket.core.Message;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;

public class String2MessageDeserializer extends JsonDeserializer<Message> {

    @Override
    public Message deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        JsonNode messageNode = p.getCodec().readTree(p);
        JsonNode headerNode = messageNode.get("header");

        int type = headerNode.get("type").intValue();

        JsonNode commandNode = headerNode.get("command");

        Command command = Command.valueOf(commandNode.get("module").shortValue(), commandNode.get("command").shortValue());

        Header header = Header.valueOf((byte) 0, headerNode.get("state").shortValue(), headerNode.get("sn").intValue(), headerNode.get("session").longValue(), command);

        byte[] body = messageNode.get("body").binaryValue();

        return Message.valueOf(header, body);
    }

}
